import sseText from "../mock/sse-text";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { Authorization } from "./server/recommend_question";

export function sseRequest(
  url: string,
  content: string,
  chat_id: string,
  onmessage: any
) {
  const abort = new AbortController();

  fetchEventSource(url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      Authorization: "Bearer " + Authorization,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      role: "assistant",
      content: content,
      user_id: "123",
      chat_id: chat_id,
    }),
    onmessage(e) {
      console.log("onmessage", e);
      onmessage(e);
    },
    onopen(res) {
      if (res.status === 401) {
        import("@/store").then((module) => {
          module.useAppStore.setState({ logined: false });
        });
        return Promise.reject();
      }
      return Promise.resolve();
    },
    signal: abort.signal,
  })
    .then((res) => {
      console.log("res", res);
    })
    .catch((err) => {
      console.log("err", err);
    });

  return abort;
}

export function mockSSEResponse(
  cb: (res: { responseMarkdown: string; status: string }) => void
) {
  const arr = [...sseText];

  function loopCallback() {
    const one = arr.shift();

    if (!one) {
      return;
    }

    setTimeout(() => {
      cb(one);
      loopCallback();
    }, 100);
  }

  loopCallback();
}
